package com.stillcoolme.basic.concurrent;


import java.util.concurrent.*;
import java.util.*;


public class TaskTest {


    // 带优先级的Callable任务
    static class PriorityCallable<T> implements Callable<T>, Comparable<PriorityCallable<T>> {
        private final Callable<T> task;
        private final int priority;

        public PriorityCallable(Callable<T> task, int priority) {
            this.task = task;
            this.priority = priority;
        }

        @Override
        public T call() throws Exception {
            return task.call();
        }

        @Override
        public int compareTo(PriorityCallable<T> other) {
            return Integer.compare(other.priority, this.priority);
        }
    }

    // 可比较的 FutureTask
    static class ComparableFutureTask<V> extends FutureTask<V> implements Comparable<ComparableFutureTask<V>> {
        private final int priority;

        public ComparableFutureTask(Callable<V> callable, int priority) {
            super(callable);
            this.priority = priority;
        }

        public ComparableFutureTask(Runnable runnable, V result, int priority) {
            super(runnable, result);
            this.priority = priority;
        }

        @Override
        public int compareTo(ComparableFutureTask<V> other) {
            return Integer.compare(other.priority, this.priority);
        }
    }

        public static void main(String[] args) throws Exception {
            // 创建线程池，使用优先级队列
            ThreadPoolExecutor executor = new ThreadPoolExecutor(
                    2, 4, 60, TimeUnit.SECONDS,
                    new PriorityBlockingQueue<>()
            );

            List<Future<String>> futures = new ArrayList<>();

            // 创建并提交带优先级的任务
            futures.add((Future<String>) executor.submit(new ComparableFutureTask<>(
                    () -> {
                        System.out.println("执行高优先级任务");
                        Thread.sleep(1000);
                        return "高优先级任务结果";
                    }, 10
            )));

            futures.add((Future<String>) executor.submit(new ComparableFutureTask<>(
                    () -> {
                        System.out.println("执行中优先级任务");
                        Thread.sleep(1000);
                        return "中优先级任务结果";
                    }, 5
            )));

            futures.add((Future<String>) executor.submit(new ComparableFutureTask<>(
                    () -> {
                        System.out.println("执行低优先级任务");
                        Thread.sleep(1000);
                        return "低优先级任务结果";
                    }, 1
            )));

            // 获取结果
            for (Future<String> future : futures) {
                String result = future.get();
                System.out.println("收到结果: " + result);
            }

            executor.shutdown();
        }

}
